﻿#region License
/*
Copyright (c) <2012> <Nercoding>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Original Code by Gastric of Dawnsong
 */
#endregion
using System;
using System.Management;
using System.Security.Principal;
using System.Diagnostics;
using AC2_MultiClient.Events;

namespace AC2_MultiClient.Managers
{

    /// <summary>
    /// Using this class forces the program to have to be run as an administrator
    /// Otherwise you get access denied
    /// </summary>
    public class ProcessMonitor : IDisposable
    {
        #region Event Watchers
        private ManagementEventWatcher startWatch = new ManagementEventWatcher(
            new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
        private ManagementEventWatcher stopWatch = new ManagementEventWatcher(
            new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"));
        public Process ReturnedProcess = null;

        // delegate declaration
        public delegate void ChangingHandler(object sender, ProcessEventArgs e);

        // event declaration
        public event ChangingHandler IncommingProcess; 

        #endregion
        /// <summary>
        /// Starts our Process Watcher
        /// </summary>
        public void Start()
        {
            startWatch.EventArrived += new EventArrivedEventHandler(startWatch_EventArrived);
            stopWatch.EventArrived += new EventArrivedEventHandler(stopWatch_EventArrived);
            startWatch.Start();
            stopWatch.Start();
        }
        /// <summary>
        /// Stops our process watcher
        /// </summary>
        public void Stop()
        {
            startWatch.Stop();
            stopWatch.Stop();
        }
        /// <summary>
        /// Runs when a Process starts on the local machine
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void startWatch_EventArrived(object sender, EventArrivedEventArgs e)
        {
            if (e.NewEvent.Properties["ProcessName"].Value.ToString().ToLower() == "ac2client.exe")
            {
                // Return this process
                int process = 0;
                int.TryParse(e.NewEvent.Properties["ProcessId"].Value.ToString(), out process);
                ProcessEventArgs ee = new ProcessEventArgs(Process.GetProcessById(process));
                IncommingProcess(this, ee);
                this.ReturnedProcess = Process.GetProcessById(process);
            }
        }
        /// <summary>
        /// Runs when a Process stops on the local machine
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void stopWatch_EventArrived(object sender, EventArrivedEventArgs e)
        {
            if (e.NewEvent.Properties["ProcessName"].Value.ToString().ToLower() == "ac2client.exe")
            {
                // Return this process
                int process = 0;
                int.TryParse(e.NewEvent.Properties["ProcessId"].Value.ToString(), out process);

                // remove this client
                Client toremove = null;
                foreach (Client c in AC2MultiClient.Clients)
                {
                    if (c.ClientProcess.Id == process)
                    {
                        toremove = c;
                    }
                }
                // Remove it
                AC2MultiClient.Clients.Remove(toremove);
            }
        }
        /// <summary>
        /// Clears our Process Var
        /// </summary>
        public void ClearProcess()
        {
            this.ReturnedProcess = null;
        }
        /// <summary>
        /// Disposes of this object
        /// </summary>
        public void Dispose()
        {
            this.Stop();
        }
    }
}
